﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using System.Diagnostics;

namespace Odyssey.Behaviors
{
    /// <summary>
    /// Extends a ButtonBase control with attached properties Command and CommandParameter in order to enable command binding.
    /// </summary>
    public class ButtonCommand 
    {

        public static object GetCommandParameter(DependencyObject obj)
        {
            return (object)obj.GetValue(CommandParameterProperty);
        }

        public static void SetCommandParameter(DependencyObject obj, object value)
        {
            obj.SetValue(CommandParameterProperty, value);
        }

        public static readonly DependencyProperty CommandParameterProperty =
            DependencyProperty.RegisterAttached("CommandParameter", typeof(object), typeof(ButtonCommand), new PropertyMetadata(null));



        public static ICommand GetCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(CommandProperty);
        }

        public static void SetCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(CommandProperty, value);
        }

        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(ButtonCommand), new PropertyMetadata(null, OnCommandChanged));

        private static void OnCommandChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            ICommand cmd = e.NewValue as ICommand;
            ButtonBase btn = o as ButtonBase;
            if (btn != null)
            {
                if (cmd == null)
                {
                    btn.Click -= OnButtonClick;
                }
                else
                {
                    btn.Click += new RoutedEventHandler(OnButtonClick);
                }
            }
        }

        static void OnButtonClick(object sender, RoutedEventArgs e)
        {
            ButtonBase btn = sender as ButtonBase;
            ICommand cmd = GetCommand(btn);
            if (cmd != null)
            {
                object param = GetCommandParameter(btn);
                cmd.Execute(param);
            }
        }


    }
}
